﻿//Copyright (c) 2010 William Liu, Enoch Ye
//William Liu <william.lyz@gmail.com>
//Enoch Ye <moonlight.enoch@gmail.com>

//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at

//       http://www.apache.org/licenses/LICENSE-2.0

//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Reflection;
//Program Libs
using GBG_DBM.UI;
using GBG_DBM.SysCheck;
using GBG_DBM.Support.BLL;
using GBG_DBM.GlobalParameters;
using GBG_DBM.Test;


namespace GBG_DBM
{
    static class Program
    {
        /// <summary>
        /// this class has been modified
        /// this class is using to contral forms' open and close
        /// due to C# Winform muti-form issue, the program needs to close some unuse forms to save the system resource
        /// </summary>
        /// 
        public static Form form = null;
        

        [STAThread]
        static void Main()
        {
            AppCheck DBCheck = new AppCheck();

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            //instance handeling
            Process instance = RunningInstance();

            //test panel
            //TestPanel testPanel = new TestPanel();
            //testPanel.Show();

            if (instance == null)
            {
                DBCheck.CheckApp();
                Backup DBbackup = new Backup(GlobalParams.DefaultBackupPath());
                if (DBCheck.IsAppCheckPass == true)
                {
                    if (DBbackup.BackupFile() == true)
                    {
                        Application.Run(new login_UI());
                    }
                    else
                    {
                        if (DialogResult.Yes == MessageBox.Show("It looks like there is something wrong when I try to backup Database", "Backup Error",
                            MessageBoxButtons.OK,
                            MessageBoxIcon.Error,
                            MessageBoxDefaultButton.Button1))
                        {
                            Application.Exit();
                        }
                    }
                }

                if (form != null)
                {
                    Application.Run(form);
                }
            }
            else
            {
                //already has one instance
                HandleRunningInstance(instance);
            }
         }

            

        #region Check runing instance

        //inport dll from system
        [DllImport("User32.dll")]
        private static extern bool ShowWindowAsync(System.IntPtr hWnd, int cmdShow);
        [DllImport("User32.dll")]
        private static extern bool SetForegroundWindow(System.IntPtr hWnd);

        //check current runing instance
        private static Process RunningInstance()
        {
            Process _currentProcess = Process.GetCurrentProcess();
            Process[] _processes = Process.GetProcessesByName(_currentProcess.ProcessName);

            //tranver currence processes
            foreach (Process process in _processes)
            {
                //if already has instance runing then ignore current paocess
                if (process.Id != _currentProcess.Id)
                {
                    //check if the new instance and old instance are come from same path/are same exe file
                    if (Assembly.GetExecutingAssembly().Location.Replace("/", "\\") == _currentProcess.MainModule.FileName)
                    {
                        //return old instance
                        return process;
                    }
                }
            }
            return null;
        }

        private static void HandleRunningInstance(Process instance)
        {
            MessageBox.Show("An instance of the Application is already running.", "Infomation",
                MessageBoxButtons.OK,
                MessageBoxIcon.Information);

            //call system api, dispaly the window
            ShowWindowAsync (instance.MainWindowHandle, 1);
            //bring window to front
            SetForegroundWindow(instance.MainWindowHandle);
        }

        #endregion
    }
}
